home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3431 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.4 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Clearing the keyboard buffer in ANSI C
  5. Date: 28 Jan 1996 15:13:12 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4egvu8INN7g3@keats.ugrad.cs.ubc.ca>
  8. References: <tfiedler-2801961347210001@205.217.163.224>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <tfiedler-2801961347210001@205.217.163.224>,
  12. Todd A. Fiedler <tfiedler@muscanet.com> wrote:
  13. >Help.
  14. >
  15. >I am a newbie to C and I can't figure out how to clear the keyboard buffer.
  16. >
  17. >I am writing a program that runs from the console and asks for user input.
  18. >Anyway, I cannot seem to get the last newline character out of the stream
  19. >before my next fscanf or fgets. I have tried fflush() to no avail. I have
  20. >even tried placing "%*s" in my fscanf string to capture the errant
  21. >newline. Still
  22. >won't work.
  23.  
  24. The standard C library knows no such thing as a keyboard. It originated on UNIX
  25. systems as a programming convenience. However, the terminal driver you are
  26. interacting with has its own line buffering that works independently of the
  27. standard I/O library. fflush() only clears the standard library's buffers, not
  28. the buffers that the underlying OS associates with your keyboard, terminal or
  29. what have you.
  30.  
  31. The more you think about it, the less it has to do with C.
  32.  
  33. The precise way to do this varies with the OS. If you are on a UNIX system, you
  34. can put the terminal in a special raw mode whereby line buffering is disabled,
  35. and each call to read() will return as soon as there are characters ready.  You
  36. can then use select() with a time-out of zero (or a small value) to poll the
  37. terminal and keep extracting characters from it until select() polls negative.
  38. Without enabling the terminal raw mode, this won't do anything, since in
  39. canonical input mode, the terminal driver will not report the presence of any
  40. input until the user hits "Enter".
  41.  
  42. If all you want is to flush that "Enter", then you can get away without
  43. massaging the terminal mode. HOwever, you will not be able to flush the partial
  44. line that the user has typed in, just everything up to the most recent newline.
  45. That may be good enough if all you are doing is line-buffered input.
  46.  
  47. >Any suggestions, help or comments would be *greatly* appreciated.
  48.  
  49. Go to a newsgroup that discusses programming details for the operating system
  50. that you use.
  51.  
  52. -- 
  53.  
  54.